package com.menglei.dailytasks.m0713;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import com.menglei.dailytasks.R;

public class BroadCastActivity extends AppCompatActivity implements View.OnClickListener {

    private Button mBtnShow;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initBroadcast();
        //toSendBroadcast();
    }

    private void toSendBroadcast() {
        //广播自定义意图:
        //隐式：发送广播时，不指定具体的广播接收者类，而是携带一些action、category或者data。例如：
//        Intent intent = new Intent();
//        intent.setAction("com.example.broadcast.MY_NOTIFICATION");
//        intent.putExtra("data", "Notice me senpai!");
//        intent.setComponent(new ComponentName("com.example.demo0713", "com.example.demo0713.receiver.MyBroadcastReceiver"));//参数为包名和类名，注意类名中要包括包名
//        sendBroadcast(intent);
        //显示：发送广播时，指定具体的广播接收者类，例如：在Activity中可通过如下语句发送广播：
        Intent intent2 = new Intent(this, MyBroadcastReceiver.class);
        intent2.setAction("com.example.broadcast.MY_NOTIFICATION");
        intent2.putExtra("data", "Notice me senpai!");
        sendBroadcast(intent2);

    }

    private void initBroadcast() {
        MyBroadcastReceiver receiver = new MyBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);   //监听飞行模式的打开与关闭
        intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED); //监听蓝牙状态与连接断开
        intentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION); //监听wifi的改变状态
        this.registerReceiver(receiver, intentFilter);
//        IntentFilter intentFilter2 = new IntentFilter();
//        intentFilter2.addAction("com.example.broadcast.MY_NOTIFICATION");
//        this.registerReceiver(receiver, intentFilter2);

    }

    private void initView() {
        mBtnShow = (Button) findViewById(R.id.btn_show);
        mBtnShow.setOnClickListener(this);
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            default:
                break;
            case R.id.btn_show:
                toSendBroadcast();
                break;
        }
    }

}